package com.sgb.zhaocai.view.demand.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.link.router.PathLogin;
import com.sgb.link.view.widget.ProjectPickerBuilder;
import com.sgb.link.view.widget.ProjectPickerView;
import com.sgb.zhaocai.R;
import com.sgb.zhaocai.base.BaseApi;
import com.sgb.zhaocai.databinding.ActivityDemandIssueBinding;
import com.sgb.zhaocai.entity.DemandIssueBean;
import com.sgb.zhaocai.entity.EquipmentListBase;
import com.sgb.zhaocai.entity.FilterListEntity;
import com.sgb.zhaocai.entity.LaborListBase;
import com.sgb.zhaocai.entity.MaterialListBase;
import com.sgb.zhaocai.entity.MechanicalListBase;
import com.sgb.zhaocai.entity.PublicTypeEntity;
import com.sgb.zhaocai.entity.PublishListBean;
import com.sgb.zhaocai.entity.ReturnTypeEntity;
import com.sgb.zhaocai.view.demand.adapter.BillEquipmentAdapter;
import com.sgb.zhaocai.view.demand.adapter.BillLaborAdapter;
import com.sgb.zhaocai.view.demand.adapter.BillMachineryAdapter;
import com.sgb.zhaocai.view.demand.adapter.BillMaterialsAdapter;
import com.swgk.core.base.AppActivity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.sgb.zhaocai.viewmodel.DemandIssueModel;
import com.swgk.core.view.entity.GoodsPublishEntity;
import com.swgk.core.view.pop.GoodsTypePopWindow;
import com.swgk.core.view.entity.MenuEntity;

/**
 * Time:2021/9/16
 * AUTHOR:F_Q
 * Description:
 */
public class DemandIssueActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    private ActivityDemandIssueBinding mBinding;
    private DemandIssueModel mModel;
    private String id;
    private int type;
    DemandIssueBean bean = new DemandIssueBean();
    private Integer NEWADDPROJECT = 101;
    private BillMaterialsAdapter billmaterialsadapter;//材料清单
    private BillEquipmentAdapter billequipmentadapter;//设备清单
    private BillMachineryAdapter billmachineryadapter;//机械清单
    private BillLaborAdapter billlaboradapter;//劳务用工清单
    //材料
    //机械
    //设备
    //劳务
    private String DEMANDTYPE = "3";
    //设备列表
    private List<PublicTypeEntity<List<PublicTypeEntity>>> equipmentList;
    private Intent intent;
    private Bundle bundle;
    //机械列表
    private List<PublicTypeEntity<List<PublicTypeEntity>>> publicTypeEntityList;

    private int SHEBEITYPE = 110;
    private int JIXIETYPE = 120;
    //机械返回数据
    private ReturnTypeEntity returnTypeEntity;

    //机械item实体类
    private MechanicalListBase mechanicalListBases;
    //设备item实体类
    private EquipmentListBase EquipmentListBases;
    //商品列表
    private List<MenuEntity<MenuEntity<MenuEntity>>> goodsTypeEntityList;
    //商品弹窗
    private GoodsTypePopWindow goodsTypePopWindow;
    private int MaterialsPos = 0;
    private int equipmentPos = 0;
    private int machineryPos = 0;

    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_demand_issue);
        mModel = new ViewModelProvider(this).get(DemandIssueModel.class);
        id = getIntent().getStringExtra("id");
        type = getIntent().getIntExtra("type", 0);
        mBinding.includeTitle.ivBack.setOnClickListener(v -> onBackPressed());
        mBinding.includeTitle.titleView.setText("需求发布");
        initPopWindow();//初始化商品弹窗信息
        ViewOnClick();//初始化点击事件
    }

    private void ViewOnClick() {
        mBinding.address.setEtEnabled(false);
        mBinding.projectType.setEtEnabled(false);
        mBinding.projectAddress.setEtEnabled(false);
        //主按钮
        mBinding.submit.setOnClickListener(this);//提交
        mBinding.storage.setOnClickListener(this);//暂存
        mBinding.addDetailed.setOnClickListener(this);//新增清单
        mBinding.applyUnit.setOnWholeItemClickListener(this);//申请单位
        mBinding.applyDepartment.setOnWholeItemClickListener(this);//申请部门
        mBinding.applyPeople.setOnWholeItemClickListener(this);//申请人
        mBinding.projectName.setOnWholeItemClickListener(this);//项目名称
        mBinding.demandType.setOnWholeItemClickListener(this);//需求类型
        mBinding.demandName.setOnWholeItemClickListener(this);//需求名称
        bean.setSource("1");
    }

    @Override
    protected void init() {
        super.init();
        if (!TextUtils.isEmpty(id)) {
            // bean.setId(id);
            mModel.geDemandinfo(this, id);
        }else {
            adapterType("3",true);
        }
    }

    @Override
    public void onClick(View v) {
        //提交
        if (v.getId() == R.id.submit) {
            if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                showDialog3();
                return;
            } else {
                //如果为空或者null标识是新数据，不等于空为编辑数据
                if (TextUtils.isEmpty(bean.getAuditStatus())) {
                    bean.setAuditStatus("2");
                    bean.setAnnounce("1");
                } else {
                    //是否为草稿状态
                    if (TextUtils.equals(bean.getAuditStatus(), "4")) {
                        bean.setAuditStatus("2");
                        bean.setAnnounce("1");
                    }
                }
                DataBean();
            }

        }
        //暂存
        if (v.getId() == R.id.storage) {
            if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                showDialog3();
                return;
            } else {
                bean.setAuditStatus("4");
                bean.setAnnounce("0");
                DataBean();
            }
        }
        //新增清单
        if (v.getId() == R.id.add_detailed) {
            AddListData(DEMANDTYPE);
        }
    }

    //提交发布数据
    private void DataBean() {
        if (TextUtils.isEmpty(mBinding.applyUnit.getContent())) {
            MToast.showToast(this, "请选择申请单位");
            return;
        }
        if (TextUtils.isEmpty(mBinding.applyPeople.getContent())) {
            MToast.showToast(this, "请选择申请人");
            return;
        }
        if (TextUtils.isEmpty(mBinding.projectName.getContent())) {
            MToast.showToast(this, "请选择项目名称");
            return;
        }
        if (TextUtils.isEmpty(mBinding.demandType.getContent())) {
            MToast.showToast(this, "请选择需求类型");
            return;
        }
        if (TextUtils.isEmpty(mBinding.demandName.getContent())) {
            MToast.showToast(this, "请输入需求名称");
            return;
        } else {
            bean.setName(mBinding.demandName.getContent());
        }
        //bean.getType() 需求类型：1、机械租赁；2、劳务用工；3、材料采购；4、分包计划；5、设备租赁
        switch (bean.getType()){
            case "1"://机械租赁
                for (MechanicalListBase data : billmachineryadapter.getDatas()) {
                    if (TextUtils.isEmpty(data.getCategoryName()) || TextUtils.isEmpty(data.getName())|| TextUtils.isEmpty(data.getSpec())
                            || TextUtils.isEmpty(data.getUnit()) || TextUtils.isEmpty(data.getItemizedUseAmount())
                            || TextUtils.isEmpty(data.getPlanUseTime())) {
                        showToastDialog();
                        return;
                    }
                }
                bean.setMaterialList(new ArrayList<>());
                bean.setEquipmentList(new ArrayList<>());
                bean.setMechanicalList(billmachineryadapter.getDatas());
                bean.setLaborList(new ArrayList<>());
                bean.setItemizedList(new ArrayList<>());
                break;
            case "2"://劳务用工
                for (LaborListBase data : billlaboradapter.getDatas()) {
                    if (TextUtils.isEmpty(data.getPartitionedProjectName()) || TextUtils.isEmpty(data.getItemProjectAffiliation())
                            || TextUtils.isEmpty(data.getUnit()) || TextUtils.isEmpty(data.getItemizedUseAmount())
                            || TextUtils.isEmpty(data.getMemo()) || TextUtils.isEmpty(data.getPlanUseTime())) {
                        showToastDialog();
                        return;
                    }
                }
                bean.setMaterialList(new ArrayList<>());
                bean.setEquipmentList(new ArrayList<>());
                bean.setMechanicalList(new ArrayList<>());
                bean.setLaborList(billlaboradapter.getDatas());
                bean.setItemizedList(new ArrayList<>());
                break;
            case "3"://材料采购
                for (MaterialListBase data : billmaterialsadapter.getDatas()) {
                    if (TextUtils.isEmpty(data.getCategoryName()) || TextUtils.isEmpty(data.getName())
                            || TextUtils.isEmpty(data.getUnit()) || TextUtils.isEmpty(data.getItemizedUseAmount())
                            || TextUtils.isEmpty(data.getPlanUseTime())) {
                        showToastDialog();
                        return;
                    }
                }
                bean.setMaterialList(billmaterialsadapter.getDatas());
                bean.setEquipmentList(new ArrayList<>());
                bean.setMechanicalList(new ArrayList<>());
                bean.setLaborList(new ArrayList<>());
                bean.setItemizedList(new ArrayList<>());
                break;
            case "5"://设备租赁
                for (EquipmentListBase data : billequipmentadapter.getDatas()) {
                    if (TextUtils.isEmpty(data.getCategoryName()) || TextUtils.isEmpty(data.getName())
                            || TextUtils.isEmpty(data.getUnit()) || TextUtils.isEmpty(data.getItemizedUseAmount())
                            || TextUtils.isEmpty(data.getPlanUseTime())) {
                        showToastDialog();
                        return;
                    }
                }
                bean.setMaterialList(new ArrayList<>());
                bean.setEquipmentList(billequipmentadapter.getDatas());
                bean.setMechanicalList(new ArrayList<>());
                bean.setLaborList(new ArrayList<>());
                bean.setItemizedList(new ArrayList<>());
                break;
        }
        mModel.getsaveOrUpdateBusinessPlan(this ,bean);
    }

    @Override
    public void OnWholeItemClick(View view) {
        //申请单位
        if (view.getId() == R.id.apply_unit) {
            mModel.getCompanyList(this, view);
        }
        //申请部门
        if (view.getId() == R.id.apply_department) {
            if (TextUtils.isEmpty(bean.getApplyCompany())) {
                MToast.showToast(this, "请选择申请单位");
                return;
            }
            mModel.getDepartmentList(this, bean.getApplyCompany(), view);
        }
        //申请人
        if (view.getId() == R.id.apply_people) {
            if (TextUtils.isEmpty(bean.getApplyCompany())) {
                MToast.showToast(this, "请选择申请单位");
                return;
            }
            if (bean.getApplyDep()!= null&&bean.getApplyDep().size()>0) {
                mModel.getUserList(this, view, TextUtils.isEmpty(bean.getApplyDep().get(0)) ? bean.getApplyCompany() : bean.getApplyDep().get(0));
            } else {
                mModel.getUserList(this, view, bean.getApplyCompany());
            }
        }
        //项目名称
        if (view.getId() == R.id.project_name) {
            mModel.getProjectNameList(this);
        }
        //需求类型
        if (view.getId() == R.id.demand_type) {
            mModel.getDemandTypeList(this, view);
        }
    }

    //新增清单信息
    private void AddListData(String demandtype) {
        switch (demandtype) {
            case "1"://机械租赁
                int size = billmachineryadapter.getDatas().size();
                if (size > 0) {
                    for (MechanicalListBase data : billmachineryadapter.getDatas()) {
                        if (TextUtils.isEmpty(data.getCategoryName()) || TextUtils.isEmpty(data.getName())
                                || TextUtils.isEmpty(data.getUnit()) || TextUtils.isEmpty(data.getItemizedUseAmount())
                                || TextUtils.isEmpty(data.getPlanUseTime())) {
                            showToastDialog();
                            return;
                        }
                    }
                }
                MechanicalListBase mechanicalbean = new MechanicalListBase(size + 1);
                mechanicalbean.setUnit("");
                mechanicalbean.setName("");
                mechanicalbean.setCategoryId("");
                mechanicalbean.setCategoryIds(new ArrayList<>());
                mechanicalbean.setSpec("");
                mechanicalbean.setItemizedUseAmount("");
                mechanicalbean.setPlanUseTime("");
                mechanicalbean.setCategoryName("");
                billmachineryadapter.getDatas().add(mechanicalbean);
                billmachineryadapter.notifyDataSetChanged();
                if (billmachineryadapter.getDatas().size()>=10){
                    mBinding.addDetailed.setVisibility(View.GONE);
                }
                break;
            case "2"://劳务用工
                int size2 = billlaboradapter.getDatas().size();
                if (size2 > 0) {
                    for (LaborListBase data : billlaboradapter.getDatas()) {
                        if (TextUtils.isEmpty(data.getPartitionedProjectName()) || TextUtils.isEmpty(data.getItemProjectAffiliation())
                                || TextUtils.isEmpty(data.getUnit()) || TextUtils.isEmpty(data.getItemizedUseAmount())
                                || TextUtils.isEmpty(data.getMemo()) || TextUtils.isEmpty(data.getPlanUseTime())) {
                            showToastDialog();
                            return;
                        }
                    }
                }
                LaborListBase laborbase = new LaborListBase(size2 + 1);
                laborbase.setPartitionedProjectName("");
                laborbase.setItemProjectAffiliation("");
                laborbase.setUnit("");
                laborbase.setItemizedUseAmount("");
                laborbase.setMemo("");
                laborbase.setPlanUseTime("");
                billlaboradapter.getDatas().add(laborbase);
                billlaboradapter.notifyDataSetChanged();
                if (billlaboradapter.getDatas().size()>=10){
                    mBinding.addDetailed.setVisibility(View.GONE);
                }
                break;
            case "3"://材料采购
                int size3 = billmaterialsadapter.getDatas().size();
                if (size3 > 0) {
                    for (MaterialListBase data : billmaterialsadapter.getDatas()) {
                        if (TextUtils.isEmpty(data.getCategoryName()) || TextUtils.isEmpty(data.getName())
                                || TextUtils.isEmpty(data.getUnit()) || TextUtils.isEmpty(data.getItemizedUseAmount())
                                || TextUtils.isEmpty(data.getPlanUseTime())) {
                            showToastDialog();
                            return;
                        }
                    }
                }
                MaterialListBase materiallist = new MaterialListBase(size3 + 1);
                materiallist.setPlanUseTime("");
                materiallist.setCategoryId("");
                materiallist.setCategoryIds(new ArrayList<>());
                materiallist.setName("");
                materiallist.setSpec("");
                materiallist.setUnit("");
                materiallist.setItemizedUseAmount("");
                materiallist.setCategoryName("");
                billmaterialsadapter.getDatas().add(materiallist);
                billmaterialsadapter.notifyDataSetChanged();
                if (billmaterialsadapter.getDatas().size()>=10){
                    mBinding.addDetailed.setVisibility(View.GONE);
                }
                break;
            case "5"://设备租赁
                int size4 = billequipmentadapter.getDatas().size();
                if (size4 > 0) {
                    for (EquipmentListBase data : billequipmentadapter.getDatas()) {
                        if (TextUtils.isEmpty(data.getCategoryName()) || TextUtils.isEmpty(data.getName())|| TextUtils.isEmpty(data.getSpec())
                                || TextUtils.isEmpty(data.getUnit()) || TextUtils.isEmpty(data.getItemizedUseAmount())
                                || TextUtils.isEmpty(data.getPlanUseTime())) {
                            showToastDialog();
                            return;
                        }
                    }
                }
                EquipmentListBase equipmentlist = new EquipmentListBase(size4 + 1);
                equipmentlist.setPlanUseTime("");
                equipmentlist.setName("");
                equipmentlist.setCategoryId("");
                equipmentlist.setCategoryIds(new ArrayList<>());
                equipmentlist.setSpec("");
                equipmentlist.setUnit("");
                equipmentlist.setItemizedUseAmount("");
                equipmentlist.setCategoryName("");
                billequipmentadapter.getDatas().add(equipmentlist);
                billequipmentadapter.notifyDataSetChanged();
                if (billequipmentadapter.getDatas().size()>=10){
                    mBinding.addDetailed.setVisibility(View.GONE);
                }
                break;
        }
    }


    /**
     * 申请单位
     *
     * @param data
     * @param view
     */
    public void setCompanyList(List<PublishListBean> data, View view) {
        showListPop("申请单位", view, data);
    }

    /**
     * 申请部门
     *
     * @param data
     * @param view
     */
    public void setDepartmentList(List<PublishListBean> data, View view) {
        showListPop("申请部门", view, data);
    }

    /**
     * 用户列表数据
     *
     * @param data
     * @param view
     */
    public void setUserList(List<PublishListBean> data, View view) {
        showListPop("申请人", view, data);
    }

    /**
     * 需求类型
     *
     * @param data
     * @param view
     */
    public void setDemandTypeList(List<PublishListBean> data, View view) {
        showListPop("需求类型", view, data);
    }

    /**
     * 项目列表
     *
     * @param data
     */
    public void setProjectNameList(List<FilterListEntity> data) {
        if(data!=null&&data.size()>0){
            showProjectNamePop("选择项目名称", data);
        }else {
            List<FilterListEntity> datas = new ArrayList<>();
            showProjectNamePop("选择项目名称", datas);
        }

    }

    private void showProjectNamePop(String titles, List<FilterListEntity> data) {
        if (data != null) {
            ProjectPickerView<FilterListEntity> mCustomerOptions = new ProjectPickerBuilder(this, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {

                    if (data!=null&&data.size()>0&&data.get(options1)!=null){
                        FilterListEntity filterListEntity = data.get(options1);
                        mBinding.projectName.setContent(filterListEntity.getProjectName() + "");
                        mBinding.projectAddress.setContent(filterListEntity.getProjectAddressName() + "");//项目地址
                        mBinding.address.setContent(filterListEntity.getAddrDetail() + "");//项目详细地址
                        mBinding.projectType.setContent(filterListEntity.getEngineeringType() + "");//工程类型
                        bean.setProjectAddress(filterListEntity.getProjectAddressName()+"");
                        bean.setProjectId(filterListEntity.getId()+"");
                        bean.setProjectName(filterListEntity.getProjectName()+"");
                        bean.setEngineeringType(filterListEntity.getEngineeringType() + "");
                        bean.setAddress(filterListEntity.getAddrDetail()+ "");
                        mBinding.llAddress.setVisibility(View.VISIBLE);
                    }else {
                        mBinding.llAddress.setVisibility(View.GONE);
                    }
                }
            }).setCancelColor(Color.parseColor("#666666")).setCancelText("取消")
                    .setSubCalSize(15)
                    .setTitleColor(Color.parseColor("#969696")).setTitleSize(15).setTitleText(titles)
                    .setSubmitColor(Color.parseColor("#5792FD")).setSubmitText("确定").build();
            mCustomerOptions.setOnAddOperate(new ProjectPickerView.OnAddOperate() {
                @Override
                public void Add() {
                    //跳转到新增项目界面
                    NewAddProjectActivity.start(DemandIssueActivity.this, NEWADDPROJECT);
                }
            });
            mCustomerOptions.setTitleText(titles);
            mCustomerOptions.setPicker(data);
            mCustomerOptions.setSelectOptions(0);
            mCustomerOptions.windowDeploy();
            mCustomerOptions.show();
        }
    }

    /**
     * 一级选择弹窗
     *
     * @param titles
     * @param inputTextView
     * @param data
     */
    private void showListPop(String titles, View inputTextView, List<PublishListBean> data) {
        if (data != null && data.size() > 0) {
            OptionsPickerView<PublishListBean> mCustomerOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    if (inputTextView.getId() == R.id.apply_unit) {//申请单位
                        mBinding.applyUnit.setContent(data.get(options1).getName());
                        bean.setApplyCompanyName(data.get(options1).getName());
                        bean.setApplyCompany(data.get(options1).getId());
                        mBinding.applyDepartment.setContent("");
                        bean.setApplyDepName("");
                        bean.setApplyDep(new ArrayList<>());
                        mBinding.applyPeople.setContent("");
                        bean.setApplyUserName("");
                        bean.setApplyUser("");
                    }
                    if (inputTextView.getId() == R.id.apply_department) {//申请部门
                        mBinding.applyDepartment.setContent(data.get(options1).getName());
                        List<String> applyDeps = new ArrayList<>();
                        applyDeps.add(data.get(options1).getId());
                        bean.setApplyDep(applyDeps);
                        bean.setApplyDepName(data.get(options1).getName());
                        mBinding.applyPeople.setContent("");
                        bean.setApplyUserName("");
                        bean.setApplyUser("");
                    }
                    if (inputTextView.getId() == R.id.apply_people) {//申请人
                        mBinding.applyPeople.setContent(data.get(options1).getName());
                        bean.setApplyUserName(data.get(options1).getName());
                        bean.setApplyUser(data.get(options1).getId());
                    }

                    if (inputTextView.getId() == R.id.demand_type) {//需求类型
                        mBinding.demandType.setContent(data.get(options1).getName());
                        bean.setType(data.get(options1).getId());
                        DEMANDTYPE = data.get(options1).getId();
                     //   if (!data.get(options1).getId().equals("3")){
                            adapterType(data.get(options1).getId(),true);
                       // }
                    }
                }
            }).setCancelColor(Color.parseColor("#666666"))
                    .setSubCalSize(15)
                    .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                    .setSubmitColor(Color.parseColor("#5792FD")).build();
            mCustomerOptions.setTitleText(titles);
            mCustomerOptions.setPicker(data);
            mCustomerOptions.setSelectOptions(0);
            mCustomerOptions.show();
        }
    }

    private void adapterType(String id,boolean isDetail) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mBinding.recyclerview.setLayoutManager(layoutManager);
        switch (id) {
            case "1"://机械租赁
                MechanicalListBase mechanicalbean1 = new MechanicalListBase(1);
                mechanicalbean1.setUnit("");
                mechanicalbean1.setName("");
                mechanicalbean1.setSpec("");
                mechanicalbean1.setItemizedUseAmount("");
                mechanicalbean1.setPlanUseTime("");
                mechanicalbean1.setCategoryName("");
                billmachineryadapter = new BillMachineryAdapter(getActivity(), null);
                mBinding.recyclerview.setAdapter(billmachineryadapter);
                if (isDetail){
                    billmachineryadapter.addData(mechanicalbean1);
                }else {
                    for (int i = 0; i < bean.getMechanicalList().size(); i++) {
                        bean.getMechanicalList().get(i).setIndex(i+1);
                    }
                    billmachineryadapter.setDatas(bean.getMechanicalList());
                }

                //机械租赁回调监听
                billmachineryadapter.setOnItemType(new BillMachineryAdapter.onItemType() {
                    @Override
                    public void MachineType(int pos) {
                        machineryPos = pos;
                        if (publicTypeEntityList != null) {
                            startActivityForResult(new Intent(getApplicationContext(), DeviceTypeActivity.class).putExtra("publicTypeEntityList", (Serializable) publicTypeEntityList), JIXIETYPE);
                        } else {
                            mModel.getMachineTypeModel(DemandIssueActivity.this);
                        }
                    }

                    @Override
                    public void Delete(int pos) {
                        //删除信息
                        if (billmachineryadapter.getDatas().size() > 1) {
                            billmachineryadapter.getDatas().remove(pos);
                            if (billmachineryadapter.getDatas().size() > 0) {
                                for (int i = 0; i < billmachineryadapter.getDatas().size(); i++) {
                                    billmachineryadapter.getDatas().get(i).setIndex(i + 1);
                                }
                            }
                            billmachineryadapter.notifyDataSetChanged();
                        }
                    }
                });
                break;
            case "2"://劳务用工
                LaborListBase laborbase1 = new LaborListBase( 1);
                laborbase1.setPartitionedProjectName("");
                laborbase1.setItemProjectAffiliation("");
                laborbase1.setUnit("");
                laborbase1.setItemizedUseAmount("");
                laborbase1.setMemo("");
                laborbase1.setPlanUseTime("");
                billlaboradapter = new BillLaborAdapter(getActivity(), null);
                mBinding.recyclerview.setAdapter(billlaboradapter);
                if (isDetail){
                    billlaboradapter.addData(laborbase1);
                }else {
                    for (int i = 0; i < bean.getLaborList().size(); i++) {
                        bean.getLaborList().get(i).setIndex(i+1);
                    }
                    billlaboradapter.setDatas(bean.getLaborList());
                }
                //劳务用工回调监听
                billlaboradapter.setOnItemType(new BillLaborAdapter.onItemType() {
                    @Override
                    public void Delete(int pos) {
                        if (billlaboradapter.getDatas().size() > 1) {
                            billlaboradapter.getDatas().remove(pos);
                            if ( billlaboradapter.getDatas().size() > 0) {
                                for (int i = 0; i <  billlaboradapter.getDatas().size(); i++) {
                                    billlaboradapter.getDatas().get(i).setIndex(i + 1);
                                }
                            }
                            billlaboradapter.notifyDataSetChanged();
                        }
                    }
                });
                break;
            case "3"://材料采购
                MaterialListBase materiallist1 = new MaterialListBase(1);
                materiallist1.setPlanUseTime("");
                materiallist1.setName("");
                materiallist1.setCategoryId("");
                materiallist1.setCategoryIds(new ArrayList<>());
                materiallist1.setSpec("");
                materiallist1.setUnit("");
                materiallist1.setItemizedUseAmount("");
                materiallist1.setCategoryName("");
                billmaterialsadapter = new BillMaterialsAdapter(this, null);
                mBinding.recyclerview.setAdapter(billmaterialsadapter);
                if (isDetail){
                    billmaterialsadapter.addData(materiallist1);
                }else {
                    for (int i = 0; i < bean.getMaterialList().size(); i++) {
                        bean.getMaterialList().get(i).setIndex(i+1);
                    }
                    billmaterialsadapter.setDatas(bean.getMaterialList());
                }

                //材料采购回调监听
                billmaterialsadapter.setOnItemType(new BillMaterialsAdapter.onItemType() {
                    @Override
                    public void MaterialsType(int pos) {
                        MaterialsPos = pos;
                        if (goodsTypeEntityList != null) {
                            showGoodsTypePop(goodsTypeEntityList);
                        } else {
                            mModel.getGoodsCategory(DemandIssueActivity.this);
                        }
                    }

                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void Delete(int pos) {
                        if (billmaterialsadapter.getDatas().size() > 1) {
                            billmaterialsadapter.getDatas().remove(pos);
                            if (billmaterialsadapter.getDatas().size() > 0) {
                                for (int i = 0; i < billmaterialsadapter.getDatas().size(); i++) {
                                    billmaterialsadapter.getDatas().get(i).setIndex(i + 1);
                                }
                            }
                            billmaterialsadapter.notifyDataSetChanged();
                        }
                    }
                });
                break;
            case "5"://设备租赁
                EquipmentListBase equipmentlist1 = new EquipmentListBase(1);
                equipmentlist1.setPlanUseTime("");
                equipmentlist1.setName("");
                equipmentlist1.setSpec("");
                equipmentlist1.setUnit("");
                equipmentlist1.setItemizedUseAmount("");
                equipmentlist1.setCategoryName("");
                billequipmentadapter = new BillEquipmentAdapter(getActivity(), null);
                mBinding.recyclerview.setAdapter(billequipmentadapter);
                if (isDetail){
                    billequipmentadapter.addData(equipmentlist1);
                }else {
                    for (int i = 0; i < bean.getEquipmentList().size(); i++) {
                        bean.getEquipmentList().get(i).setIndex(i+1);
                    }
                    billequipmentadapter.setDatas(bean.getEquipmentList());
                }

                //设备租赁回调监听
                billequipmentadapter.setOnItemType(new BillEquipmentAdapter.onItemType() {
                    @Override
                    public void DeviceType(int pos) {
                        equipmentPos = pos;
                        if (equipmentList != null) {
                            startActivityForResult(new Intent(getApplicationContext(), DeviceTypeActivity.class).putExtra("publicTypeEntityList", (Serializable) equipmentList), SHEBEITYPE);
                        } else {
                            mModel.getParentDeviceType(DemandIssueActivity.this);
                        }
                    }

                    @Override
                    public void Delete(int pos) {
                        if (billequipmentadapter.getDatas().size() > 1) {
                            billequipmentadapter.getDatas().remove(pos);
                            if (billequipmentadapter.getDatas().size() > 0) {
                                for (int i = 0; i < billequipmentadapter.getDatas().size(); i++) {
                                    billequipmentadapter.getDatas().get(i).setIndex(i + 1);
                                }
                            }
                            billequipmentadapter.notifyDataSetChanged();
                        }
                    }
                });
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == NEWADDPROJECT) {
                //更新项目列表
                mModel.getProjectNameList(this);
            }
            //机械租赁
            if (requestCode == JIXIETYPE) {
                returnTypeEntity = (ReturnTypeEntity) data.getSerializableExtra("data");
                MechanicalListBase mechanicalListBase = billmachineryadapter.getDatas().get(machineryPos);
                mechanicalListBase.setCategoryName(returnTypeEntity.getFirstName() + "/" + returnTypeEntity.getSecondName());
                mechanicalListBase.setCategoryId(returnTypeEntity.getSecondNo());
                List<String> CategoryIds = new ArrayList<>();
                CategoryIds.add(returnTypeEntity.getFirstNo());
                CategoryIds.add(returnTypeEntity.getSecondNo());
                mechanicalListBase.setCategoryIds(CategoryIds);
                billmachineryadapter.notifyDataSetChanged();
            }
            //设备租赁
            if (requestCode == SHEBEITYPE) {
                returnTypeEntity = (ReturnTypeEntity) data.getSerializableExtra("data");
                EquipmentListBase equipmentListBase = billequipmentadapter.getDatas().get(equipmentPos);
                equipmentListBase.setCategoryName(returnTypeEntity.getFirstName() + "/" + returnTypeEntity.getSecondName());
                equipmentListBase.setCategoryId(returnTypeEntity.getSecondNo());
                List<String> CategoryIds = new ArrayList<>();
                CategoryIds.add(returnTypeEntity.getFirstNo());
                CategoryIds.add(returnTypeEntity.getSecondNo());
                equipmentListBase.setCategoryIds(CategoryIds);
                billequipmentadapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onBackPressed() {
        initDialog();
    }

    public void initDialog() {
        new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                .setTitle("温馨提示")
                .setMsg("此操作将丢失当前表单填写内容,\n是否继续?")
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {
                        if (type == 2) {
                            setResult(RESULT_OK, new Intent());
                            DemandIssueActivity.this.finish();
                        } else {
                             mModel.getWebH5(DemandIssueActivity.this, id);
                        }
                    }

                    @Override
                    public void onLeftClick() {
                        return;
                    }
                }).show();
    }


    //未登录弹框跳转认证
    public void showDialog3() {
        View view = View.inflate(this, R.layout.dialog_two_btn, null);
        RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
        tv_title.setVisibility(View.VISIBLE);
        tv_title.setText("温馨提示");
        TextView tv_logout_confirm = (TextView) view.findViewById(R.id.tv_logout_confirm);
        tv_logout_confirm.setText("确定");
        TextView tv_logout_cancel = (TextView) view.findViewById(R.id.tv_logout_cancel);
        tv_message.setText("未登录，请先登录。");
        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityJump.startActivity(PathLogin.VerificationCodeLoginActivity);
                roundCornerDialog.dismiss();
            }
        });
        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    //未登录弹框跳转认证
    public void showToastDialog() {
        View view = View.inflate(this, R.layout.dialog_toast, null);
        RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
        TextView tv_logout_confirm = (TextView) view.findViewById(R.id.tv_logout_confirm);
        tv_logout_confirm.setText("知道了");
        TextView tv_logout_cancel = (TextView) view.findViewById(R.id.tv_logout_cancel);
        tv_message.setText("还有必填字段未填写,请先填写后再提交");
        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    //设备
    public void setParentDeviceType(List<PublicTypeEntity<List<PublicTypeEntity>>> data) {
        this.equipmentList = data;
        if (intent == null) {
            intent = new Intent();
        }
        startActivityForResult(new Intent(getApplicationContext(), DeviceTypeActivity.class).putExtra("publicTypeEntityList", (Serializable) equipmentList), SHEBEITYPE);
    }

    //机械
    public void setMachineTypeModel(List<PublicTypeEntity<List<PublicTypeEntity>>> data) {
        this.publicTypeEntityList = data;
        if (intent == null) {
            intent = new Intent();
        }
        startActivityForResult(new Intent(getApplicationContext(), DeviceTypeActivity.class).putExtra("publicTypeEntityList", (Serializable) publicTypeEntityList), JIXIETYPE);
    }

    /**
     * 商品返回数据信息
     *
     * @param data
     */
    public void showGoodsTypePop(List<MenuEntity<MenuEntity<MenuEntity>>> data) {
        this.goodsTypeEntityList = data;
        if (!goodsTypePopWindow.isShowing()) {
            goodsTypePopWindow.showDownPopwindow(mBinding.grayLayout, true);
        }
        goodsTypePopWindow.setData(goodsTypeEntityList);
    }


    private void initPopWindow() {
        if (goodsTypePopWindow == null) {
            goodsTypePopWindow = new GoodsTypePopWindow(this);
        }
        goodsTypePopWindow.setBgView(mBinding.grayLayout);
        goodsTypePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                GoodsPublishEntity goodsPublishEntity = (GoodsPublishEntity) key1;
                MaterialListBase materialListBase = billmaterialsadapter.getDatas().get(MaterialsPos);
                materialListBase.setCategoryId(goodsPublishEntity.getCid3());
                List<Integer> categoryids = new ArrayList<>();
                if (!TextUtils.isEmpty(goodsPublishEntity.getCid1())) {
                    categoryids.add(Integer.parseInt(goodsPublishEntity.getCid1()));
                }
                if (!TextUtils.isEmpty(goodsPublishEntity.getCid2())) {
                    categoryids.add(Integer.parseInt(goodsPublishEntity.getCid2()));
                }
                //三级分类业务名称、业务编号
                if (!TextUtils.isEmpty(goodsPublishEntity.getCid3())) {
                    categoryids.add(Integer.parseInt(goodsPublishEntity.getCid3()));
                }
                materialListBase.setCategoryIds(categoryids);
                materialListBase.setCategoryName(goodsPublishEntity.getCid1Name() + "/" + goodsPublishEntity.getCid2Name() + "/" + goodsPublishEntity.getCid3Name());
                //重置信息
                materialListBase.setItemizedUseAmount("");
                materialListBase.setName("");
                materialListBase.setPlanUseTime("");
                materialListBase.setSpec("");
                materialListBase.setUnit("");
                billmaterialsadapter.notifyDataSetChanged();
            }
        });
    }

    //发布成功
    public void setSaveOrUpdateBusinessPlan(String auditStatus) {
        if (type == 2) {
            //auditStatus	流程审批状态（2、发布通过；4、草稿暂存）
            if (TextUtils.equals(auditStatus, "2")) {
                MToast.showToast(this, "提交成功");
            } else {
                MToast.showToast(this, "暂存成功");
            }
            setResult(RESULT_OK, new Intent());
            finish();
        } else {
            mModel.getWebH5(DemandIssueActivity.this, id);
        }
    }

    //跳转到详情
    public void onSuccess(String webUrl) {
        finish();
        BaseApi.startWeb(this, webUrl);
    }

    public void setDemandinfo(DemandIssueBean data) {
        String typename = "";
        if (data!=null){
            bean = data;
            mBinding.applyUnit.setContent(data.getApplyCompanyName()+"");//申请单位
            mBinding.applyDepartment.setContent(data.getApplyDepName()+"");//申请部门
            mBinding.applyPeople.setContent(data.getApplyUserName()+"");//申请人
            mBinding.projectName.setContent(data.getProjectName()+"");//项目名称
            mBinding.projectAddress.setContent(data.getProjectAddress()+"");//项目地址
            mBinding.address.setContent(data.getAddrDetail()+"");//详细地址
            mBinding.projectType.setContent(data.getEngineeringType()+"");//工程类型
            bean.setAddress(data.getAddrDetail()+ "");
            //需求类型：1、机械租赁；2、劳务用工；3、材料采购；4、分包计划；5、设备租赁
            switch (data.getType()){
                case "1":
                    typename = "机械租赁";
                    break;
                case "2":
                    typename = "劳务用工";
                    break;
                case "3":
                    typename = "材料采购";
                    break;
                case "5":
                    typename = "设备租赁";
                    break;
            }
            mBinding.demandType.setContent(typename+"");//需求类型
            mBinding.demandName.setContent(data.getName()+"");//需求名称
            mBinding.llAddress.setVisibility(View.VISIBLE);
            adapterType(data.getType(),false);
        }
    }
}
